package com.itheima.reggie.interceptor;

/**
 * @Classname LoginCheckInterceptor
 * @Description TODO
 * @Date 2023/3/1 16:36
 * @Created by 11404
 */

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component // 登录权限拦截器
public class LoginCheckInterceptor implements HandlerInterceptor {

    // 拦截方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取session中用户信息
       Employee currentEmp = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        // 2.没有登录，拦截
        if (currentEmp == null) {
            // 2-1 设置返回信息
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            // 2-2 转为json
            String json = JSON.toJSONString(resultInfo);
            // 2-3 返回
            response.getWriter().write(json);
            // 拦截
            return false;
        }

        //储存当前线程信息,这里放入currentEmp，需要把上面的数据类型强转
        EmployeeHolder.set(currentEmp);

        // 3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 从线程内移除
        EmployeeHolder.remove();
    }
}
